package 两个链表相加;


/**
 * @author 冷加宝
 * @version 1.0
 */
public class AddTwoNumbers {

    public static class ListNode{
        int val;
        ListNode next;
        public ListNode(int val){
            this.val = val;
        }

        public ListNode(int val, ListNode next){
            this.val = val;
            this.next = next;
        }
    }

    public static ListNode addTwoNumbersByList(ListNode h1, ListNode h2){
        ListNode ans = null, cur = null;
        int carry = 0;//进位
        for(int sum, val; //声明变量
            h1 != null || h2 != null; //终止条件
            h1= h1 == null ? null : h1.next, //每一步h1的跳转
            h2 = h2 == null ? null : h2.next //每一步h2的跳转
        ){
            sum = carry
                    + (h1 == null ? 0 : h1.val)
                    + (h2 == null ? 0 : h2.val);
            carry = sum / 10;
            val = sum % 10;

            if(ans == null){
                ans = new ListNode(val);
                cur = ans;
            }else{
                cur.next = new ListNode(val);
                cur = cur.next;
            }
        }
        if(carry == 1){
            cur.next = new ListNode(1);
        }
        return ans;
    }
}
